package com.rongchuang.service;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.rongchuang.dto.ActivityAlbumDTO;
import com.rongchuang.entity.ActivityAlbum;
import com.rongchuang.entity.QActivityAlbum;
import com.rongchuang.repository.ActivityAlbumRepository;
import com.rongchuang.util.ConverterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ActivityAlbumService {

    @Autowired
    private ActivityAlbumRepository activityAlbumRepository;

    @Autowired
    private JPAQueryFactory queryFactory;

    /**
     * 分页查询
     */
    public Page<ActivityAlbumDTO> pageSearch(int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        QActivityAlbum activityAlbum = QActivityAlbum.activityAlbum;
        BooleanBuilder builder = new BooleanBuilder();
        List<ActivityAlbum> activityAlbums = queryFactory
                .selectFrom(activityAlbum)
                .where(builder)
                .offset((long) pageNum * pageSize)
                .limit(pageSize)
                .orderBy(activityAlbum.id.desc())
                .fetch();
        long total = queryFactory
                .selectFrom(activityAlbum)
                .where(builder)
                .fetchCount();
        List<ActivityAlbumDTO> activityAlbumDTOS = ConverterUtil.convertToList(activityAlbums, ActivityAlbumDTO.class);
        return new PageImpl<>(activityAlbumDTOS, pageable, total);
    }

    /**
     * 保存活动相册
     */
    public void modifyActivityAlbum(ActivityAlbumDTO activityAlbumDTO) {
        ActivityAlbum activityAlbum = ConverterUtil.convertTo(activityAlbumDTO, ActivityAlbum.class);
        activityAlbumRepository.save(activityAlbum);
    }

    /**
     * 获取活动相册
     * @param id 商会id
     */
    public ActivityAlbumDTO getDetail(Long id) {
        ActivityAlbum activityAlbum = activityAlbumRepository.getById(id);
        return ConverterUtil.convertTo(activityAlbum, ActivityAlbumDTO.class);
    }
}
